// 用来监控输入框的状态，全部为 true 时显示提交按钮提交数据
// let boardState = false;
// let cpuState = false;
// let fanState = false;
// let menState = false;
// let wholeState = false;
// let diskState = false;
// let powerState = false;
// let showState = false;

// import {constName} from "../../../golang.org/x/tools/internal/lsp/protocol/typescript/util";

let boardHeader = "LB";
let cpuHeader = "LC";
let fanHeader = "LF";
let menHeader = "LN";
let DPHeader = "DP";

let wholeHeader = "WM";
let diskHeader = "LD";
let powerHeader = "LP";
let showHeader = "LX";
let versionInfo = "";

// todo

//todo

// 附件主条码提交按钮事件
function annex_code_btn(val) {
    var reqSonCodeData = {};
    var annexCodeData = $('#annexHostCode').val().split(" ");
    var cpuCodeData = $('#cpu_code').val().split(" ");
    var fanCodeData = $('#fan_code').val().split(" ");
    var ramCodeData = $('#ram_code').val().split(" ");
    reqSonCodeData["hostCode"] = "";
    // reqSonCodeData["codeType"] = 0;
    reqSonCodeData["annexHostCodeDat"] = annexCodeData.slice(0, annexCodeData.length - 1)[0];
    // reqSonCodeData["bVersion"]=versionInfo;
    // reqSonCodeData[annexCodeData.slice(0, annexCodeData.length - 1)[0]] = {
    reqSonCodeData["diskCodeList"] = cpuCodeData.slice(0, cpuCodeData.length - 1);
    reqSonCodeData["powerCodeList"] = fanCodeData.slice(0, fanCodeData.length - 1);
    reqSonCodeData["showCodeList"] = ramCodeData.slice(0, ramCodeData.length - 1);
    reqSonCodeData["editType"] = 0;
    // }
    console.log(reqSonCodeData)
    bindCodeAjaxPostReq(reqSonCodeData, ajaxCallBackFunc, 0);
}

// 整机主条码按钮提交事件
function host_code_btn(val) {
    var reqHostCodeData = {};
    var hostCodeDat = $("#hostCode").val().split(" ");
    var annexHostCodeDat = $("#annex_host_code").val().split(" ");
    var diskCodeDat = $("#annex_disk_code").val().split(" ");
    var powerCodeDat = $("#annex_power_code").val().split(" ");
    var showCodeDat = $("#show_host").val().split(" ");
    // reqHostCodeData["codeType"] = 1;
    reqHostCodeData["hostCode"] = hostCodeDat.slice(0, hostCodeDat.length - 1)[0];
    // reqHostCodeData["bVersion"]=versionInfo;
    // reqHostCodeData[hostCodeDat.slice(0, hostCodeDat.length - 1)[0]] = {"annexHostCodeDat": annexHostCodeDat.slice(0, annexHostCodeDat.length - 1)[0]}
    reqHostCodeData["annexHostCodeDat"] = annexHostCodeDat.slice(0, annexHostCodeDat.length - 1)[0]
    // reqHostCodeData[annexHostCodeDat.slice(0, annexHostCodeDat.length - 1)[0]] = {
    reqHostCodeData["diskCodeList"] = diskCodeDat.slice(0, diskCodeDat.length - 1);
    reqHostCodeData["powerCodeList"] = powerCodeDat.slice(0, powerCodeDat.length - 1);
    reqHostCodeData["showCodeList"] = showCodeDat.slice(0, showCodeDat.length - 1);
    reqHostCodeData["editType"] = 1;
    // }
    bindCodeAjaxPostReq(reqHostCodeData, ajaxCallBackFunc, 1);
}

// todo 新增 ======================================================================
function duli_code_btn(val) {
    var duliCodeData = {};
    var duliHostCode = $("#powerHostCode").val().split(" ");
    var duliSonCode = $("#power_code").val().split(" ")
    duliCodeData["hostCode"] = duliHostCode.slice(0, duliHostCode.length - 1)[0]
    duliCodeData["diskCodeList"] = "";
    duliCodeData["diskCodeList"] = duliSonCode.slice(0, duliSonCode.length - 1);
    duliCodeData["powerCodeList"] = [];
    duliCodeData["showCodeList"] = [];
    duliCodeData["editType"] = 2;
    bindCodeAjaxPostReq(duliCodeData, ajaxCallBackFunc, 2);
}
// ====================================================================================

// 实时监控选择框数据变化情况，根据选择的内容展示不同的条码输入框
$(() => {
    $(".choose_select,.choose_select_version").change(() => {
        versionInfo = $(".choose_select_version").val();
        var chooseVal = $(".choose_station").children("div").children("div").children(".choose_select").val();
        if (chooseVal === null) {
            return;
        }
        if ($('.choose_select').val() === "" || versionInfo === "") {
            $(".bind_panel,.bind_component,.bind_annex,.bind_power").css("display", "none");
        } else if (chooseVal.split(",")[1] === "主板套件" && versionInfo !== null) {
            $(".bind_panel,.bind_annex").css("display", "block");
            $(".bind_component,.bind_power").css("display", "none");
        } else if (chooseVal.split(",")[1] === "独立套件" && versionInfo !== null) {
            $(".bind_component,.bind_annex").css("display", "none");
            $(".bind_panel,.bind_power").css("display", "block");
        } else if (chooseVal.split(",")[1] === "成品套件" && versionInfo !== null) {
            $(".bind_annex,.bind_power").css("display", "none");
            $(".bind_panel,.bind_component").css("display", "block");
        }
    });
});

// 实时监听输入框数据变化事件
$(() => {
    // 主板条码输入框检查事件
    $("#annexHostCode").on("input propertychange", () => {
        var annexHostCode = $('#annexHostCode');
        setTimeout(function () {
            checkInputDat(annexHostCode, boardHeader)
        }, 500);
        // if (annexHostCode.prop("disabled") === true) {
        //     boardState = true;
        // }
        // showBtn(0);
        // 请求的数据结构需要重构
        bindCodeAjaxGetReq({
            "gongwei": 0,
            "cfgId": $(".choose_select_version").val(),
            "hostCode": $.trim($("#annexHostCode").val())
        }, ajaxGetCallBackFunc, 0);
    });
    // cpu 条码输入框检查事件
    $("#cpu_code").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#cpu_code"), cpuHeader)
        }, 500);
        // 判断当前输入框是否封闭
        // if ($('#cpu_code').prop("disabled") === true) {
        //     cpuState = true;
        // }
        // showBtn(0);
    });
    // 散热器输入框检查事件
    $("#fan_code").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#fan_code"), fanHeader)
        }, 500);
        //
        // if ($('#fan_code').prop("disabled") === true) {
        //     fanState = true;
        // }
        // showBtn(0);
    });
    // 内存输入框检查事件
    $("#ram_code").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#ram_code"), menHeader)
        }, 500);
        // if ($('#ram_code').prop("disabled") === true) {
        //     menState = true;
        // }
        // showBtn(0);
    });

    // 整机主条码输入框检查事件
    $("#hostCode").on("input propertychange", () => {
        var hostCode = $("#hostCode");
        setTimeout(function () {
            checkInputDat(hostCode, wholeHeader)
        }, 500);
        // if (hostCode.prop("disabled") === true) {
        //     wholeState = true;
        // }
        // // 请求的数据结构需要重构
        bindCodeAjaxGetReq({
            "gongwei": 1,
            "cfgId": $(".choose_select_version").val(),
            "hostCode": $.trim($('#hostCode').val())
        }, ajaxGetCallBackFunc, 1);
    })
    // 成品附件主条码输入框检查事件
    $("#annex_host_code").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#annex_host_code"), boardHeader)
        }, 500);
        // if ($('#annex_host_code').prop("disabled") === true) {
        //     wholeState = true;
        // }
    })
    // 硬盘输入框检查事件
    $("#annex_disk_code").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#annex_disk_code"), diskHeader)
        }, 500);
        // if ($('#annex_disk_code').prop("disabled") === true) {
        //     diskState = true;
        // }
        // showBtn(1);
    });
    // 电源输入框检查事件
    $("#annex_power_code").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#annex_power_code"), powerHeader)
        }, 500);
        // if ($('#annex_power_code').prop("disabled") === true) {
        //     powerState = true;
        // }
        // showBtn(1);
    });
    // 显卡输入框检查事件
    $("#show_host").on("input propertychange", () => {
        setTimeout(function () {
            checkInputDat($("#show_host"), showHeader)
        }, 500);
        // if ($('#show_host').prop("disabled") === true) {
        //     showState = true;
        // }
        // showBtn(1);
    });

    $("#powerHostCode").on("input propertychange", () => {
        var powerHostCode = $("#powerHostCode");
        setTimeout(function () {
            againInputDuPin(powerHostCode)
        }, 500);
        // 还需获取用量
        bindCodeAjaxGetReq({
            "gongwei": 2,
            "cfgId": $(".choose_select_version").val(),
            "hostCode": $.trim($('#powerHostCode').val())
        }, ajaxGetCallBackFunc, 2);
    });
    $("#power_code").on("input propertychange", () => {
        setTimeout(function () {
            againInputDuPin($('#power_code'))
        }, 500);
    });
});

function againInputDuPin(dom) {
    let cont = Number(dom.siblings("span").text());
    if (dom.siblings("span").text() === "") {
        dom.attr("disabled", "disabled");
        // dom.siblings("span").text("");
        // 输入完成更改输入框背景色
        dom.css("background-color", "honeydew");
    }
    var datLen = dom.val().split(" ").length;
    dom.val(dom.val().trim()+ " ");
    // 检查输入的值是否已 L 开头，
    if (dom.val().split(" ")[datLen - 1].substring(0, 1) !== "L") {
        var num = cont - 1;
        dom.siblings("span").text(num + 1);
    } else {
        num = cont - 1;
        dom.siblings("span").text(num);
    }
    // var num = Number(dom.siblings("span").text());
    if (cont === 0) {
        dom.attr("disabled", "disabled");
        dom.siblings("span").text("");
        // 输入完成更改输入框背景色
        dom.css("background-color", "honeydew");
    }
}

// 检查输入框实现函数
function checkInputDat(dom, str) {
    // 获取输入框中的内容(数组)并去除按 " " 分割后数组中最后的空格
    var dataLen = dom.val().split(" ").length;

    // 自动在的输入数据的后面加上,
    dom.val(dom.val().trim() + " ");

    // 修改用量数字,当用量为 0 时禁用输入框
    // if (dom.siblings("span").text() !== " ") {  // todo 判断获取的内容是否为空格,为空格则不更变数据
    var num = Number(dom.siblings("span").text()) - 1;
    dom.siblings("span").text(num);  // 修改用量数字
    // }
    if (num === 0) {
        dom.attr("disabled", "disabled");
        dom.siblings("span").text("");
        // 输入完成更改输入框背景色
        dom.css("background-color", "honeydew");
    }

    // 输入前先检查输入框的值是否已 Lx 开头
    if (dataLen === 1) {
        if (dom.val().split(" ")[dataLen - 1].substring(0, 2) !== str) {
            // $("#component_info_err,#component_err").css("display", "block").empty().text("扫描的二维码信息非法，请扫入正确的二维码信息！").delay(4000).fadeOut();
            dom.siblings("span").text(num + 1);
            dom.val("");
        }
        if (dom.siblings("span").text() === "") {
            dom.attr("disabled", "disabled");
            // 输入完成更改输入框背景色
            dom.css("background-color", "honeydew");
        }
    }
    if (dataLen !== 1) {
        if (dom.val().split(" ")[dataLen - 1].substring(0, 2) !== str) {
            var newData = dom.val().split(" ").slice(0, dataLen - 1).join(" ");
            // $("#component_info_err,#component_err").css("display", "block").empty().text("扫描的二维码信息非法，请扫入正确的二维码信息！").delay(4000).fadeOut();
            dom.val(newData + " ");
            dom.siblings("span").text(num + 1);
            dom.attr("disabled", false);
        }
    }
}

// ajax 请求函数绑定条码方法封装
function bindCodeAjaxPostReq(data, callBackFunc, domType) {
    $.ajax({
        type: "POST",
        url: "/admin/bindCode",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: (ret) => {
            callBackFunc(ret, domType);
        },
    });
}

// ajax 根据主条码获取子条码用量方法封装
function bindCodeAjaxGetReq(reqDat, callBackFunc, domType) {
    $.ajax({
        type: "GET",
        url: "/admin/getSonCodeDosage",
        // contentType: "application/json",
        dataType: "json",
        data: reqDat,
        success: (ret) => {
            // 返回的数据格式应为 {"子件1": num,"子件2": num,...}
            callBackFunc(ret, domType);
        }
    });
}

// ajax post 请求回调函数
function ajaxCallBackFunc(ret, domType) {
    if (ret["success"] !== "") {
        var inputGroup = ""
        // 类型等于 0 表示需要清空附件主条码绑.split(" ");定页面的输入框，否则清空整机条码绑定页面输入框
        if (domType === 0) {
            // 更新数据库成功清空输入框中的内容，并重新显示
            inputGroup = $('#annexHostCode,#cpu_code,#fan_code,#ram_code')
            inputGroup.val("");
            inputGroup.removeAttr("disabled");
            inputGroup.css("background-color", "#fff");
            $(".cpu > div > .component_num").empty().text("");
            $(".fan > div > .component_num").empty().text("");
            $(".ram > div > .component_num").empty().text("");
        } if (domType === 1) {
            inputGroup = $('#hostCode,#annex_host_code,#annex_disk_code,#annex_power_code,#show_host');
            inputGroup.val("");
            inputGroup.removeAttr("disabled");
            inputGroup.css("background-color", "#fff");
            $(".disk_host > div .component_num").empty().text("");
            $(".power_host > div .component_num").empty().text("");
            $(".show_host > div .component_num").empty().text("");
        } else {
            inputGroup = $("#powerHostCode,#power_code");
            inputGroup.val("");
            inputGroup.removeAttr("disabled");
            inputGroup.css("background-color", "#fff");
            $(".duli > div > .component_num").empty().text("");
            $("#duli_info_err").css("display", "block").empty().text("绑定成功").delay(6000).fadeOut();
        }
        // $(".component_info_submit_btnz,.component_submit_btn > button").css("display", "none");
    } else {
        // 抛出错误重新显示提交按钮，可以在工程处处理后套错误后让人手动提交
        $("#component_info_err,#component_err,#duli_info_err").css("display", "block").empty().text(ret["errMsg"]).delay(6000).fadeOut();
        $(".component_info_submit_btnz,.component_submit_btn > button").css("display", "block");
    }
}

// ajax get 请求回调函数
function ajaxGetCallBackFunc(ret, domType) {
    if (ret["success"] !== "") {
        if (domType === 0) {
            for (var dict in ret["success"]) {
                if (ret["success"][dict]["mater_type_name"] === "CPU") {
                    $(".cpu > div > .component_num").empty().text(ret["success"][dict]["dosage"]);
                } else if (ret["success"][dict]["mater_type_name"] === "散热器") {
                    $(".fan > div > .component_num").empty().text(ret["success"][dict]["dosage"]);
                } else if (ret["success"][dict]["mater_type_name"] === "内存") {
                    $(".ram > div > .component_num").empty().text(ret["success"][dict]["dosage"]);
                }
            }
        } else if (domType === 1) {
            let guTaiDiskDosage = 0;
            let jiXieDiskDosage = 0;
            for (var val in ret["success"]) {
                if (ret["success"][val]["mater_type_name"] === "固态硬盘") {
                    guTaiDiskDosage = ret["success"][val]["dosage"]
                } else if (ret["success"][val]["mater_type_name"] === "硬盘") {
                    jiXieDiskDosage = ret["success"][val]["dosage"]
                }
                if (ret["success"][val]["mater_type_name"] === "硬盘") {
                    $(".disk_host > div .component_num").empty().text(guTaiDiskDosage + jiXieDiskDosage);
                } else if (ret["success"][val]["mater_type_name"] === "电源") {
                    $(".power_host > div .component_num").empty().text(ret["success"][val]["dosage"]);
                } else if (ret["success"][val]["mater_type_name"] === "显卡") {
                    $(".show_host > div .component_num").empty().text(ret["success"][val]["dosage"]);
                } else if (ret["success"][val]["mater_type_name"] === "固态硬盘") {
                    $(".disk_host > div .component_num").empty().text($("#annex_disk_code").val() + ret["success"][val]["dosage"]);
                }
            }
        } else {
            for (var v in ret["success"]) {
                $(".duli > div > .component_num").empty().text(ret["success"][v]["dosage"]);
            }
        }
    } else {
        $("#component_info_err,#component_err,#duli_info_err").css("display", "block").empty().text(ret["errMsg"]).delay(6000).fadeOut();
    }
}

